package com.renfei.ffmpegvideoplayer;

import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.renfei.ffmpegvideoplayer.listener.OnPlayerCompleteListener;
import com.renfei.ffmpegvideoplayer.listener.OnPlayerErrorListener;
import com.renfei.ffmpegvideoplayer.listener.OnPlayerLoadListener;
import com.renfei.ffmpegvideoplayer.listener.OnPlayerParparedListener;
import com.renfei.ffmpegvideoplayer.listener.OnPlayerStatusChangeListener;
import com.renfei.ffmpegvideoplayer.listener.OnVideoPlayInfoListener;
import com.renfei.ffmpegvideoplayer.listener.OnYuvDataCallBackListener;
import com.renfei.ffmpegvideoplayer.util.MuteEnum;
import com.renfei.ffmpegvideoplayer.util.TimeUtil;

import java.io.File;
import java.lang.ref.WeakReference;
import java.time.Duration;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VideoPlayActivity extends AppCompatActivity {
    private static final String TAG = VideoPlayActivity.class.getSimpleName();

    @BindView(R.id.glSurfaceView)
    VideoPlayGlSurfaceView glSurfaceView;
    @BindView(R.id.tv_current_time)
    TextView tvCurrentTime;
    @BindView(R.id.tv_seek_bar)
    SeekBar tvSeekBar;
    @BindView(R.id.tv_total_time)
    TextView tvTotalTime;
    @BindView(R.id.seek_bar_layId)
    LinearLayout seekBarLayId;
    @BindView(R.id.tv_play)
    TextView tvPlay;
    @BindView(R.id.tv_pause)
    TextView tvPause;
    @BindView(R.id.tv_resume)
    TextView tvResume;
    @BindView(R.id.tv_stop)
    TextView tvStop;
    @BindView(R.id.tv_current_Volume)
    TextView tvCurrentVolume;
    @BindView(R.id.seekBarVolume)
    SeekBar seekBarVolume;
    @BindView(R.id.btn_channel_left)
    Button btnChannelLeft;
    @BindView(R.id.btn_channel_right)
    Button btnChannelRight;
    @BindView(R.id.btn_channel_center)
    Button btnChannelCenter;

    private FFmpegPlayer fFmpegPlayer;
    private PlayTimeHandler playTimeHandler;

    private boolean isSeekBar = false;
    private int currentPosition=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_play);
        ButterKnife.bind(this);

        fFmpegPlayer = new FFmpegPlayer();
        fFmpegPlayer.setGlSurfaceView(glSurfaceView);

        seekBarVolume.setProgress(50);
        fFmpegPlayer.setVolume(50);
        fFmpegPlayer.setMute(MuteEnum.MUTE_CENTER);

        tvCurrentVolume.setText("音量:" + fFmpegPlayer.getVolume() + "%");
        fFmpegPlayer.setOnPlayerParparedListener(new OnPlayerParparedListener() {
            @Override
            public void onParpared() {
                Log.e(TAG, "onParpared :开始加载视频资源 ");

                Log.e(TAG, "开始播放: ");

                fFmpegPlayer.startPlay();
            }
        });
        fFmpegPlayer.setOnPlayerLoadListener(new OnPlayerLoadListener() {
            @Override
            public void onLoad(boolean load) {
                if (load) {
                    Log.e(TAG, "加载中...");
                } else {

                    Log.e(TAG, "加载已完成: ");
                }

            }
        });
        fFmpegPlayer.setOnPlayerErrorListener(new OnPlayerErrorListener() {
            @Override
            public void onError(int code, String msg) {
                Log.e(TAG, "code: "+code +"     msg: "+msg);
            }
        });
        fFmpegPlayer.setOnPlayerStatusChangeListener(new OnPlayerStatusChangeListener() {
            @Override
            public void onPause(boolean isPause) {
                if (isPause){
                    Log.e(TAG, "暂停播放: ");
                }else {
                    Log.e(TAG, "开始播放: ");
                }
            }
        });
        fFmpegPlayer.setOnPlayerCompleteListener(new OnPlayerCompleteListener() {
            @Override
            public void onComplete() {
                Log.e(TAG, "onComplete 方法回调完成: ");
            }
        });
        fFmpegPlayer.setOnYuvDataCallBackListener(new OnYuvDataCallBackListener() {
            @Override
            public void onYuvDataCallBack(int width, int height, byte[] y, byte[] u, byte[] v) {

            }
        });
        fFmpegPlayer.setOnVideoPlayInfoListener(new OnVideoPlayInfoListener() {
            @Override
            public void onVideoPlayInfo(VideoTimeInfo timeInfo) {

                Log.e(TAG, "onVideoPlayInfo: currentTime "+timeInfo.getCurrentTime()
                    +   "   totalTime = "+timeInfo.getTotalTime());
                Message message = new Message();
                message.what = 0;
                message.obj = timeInfo;
                playTimeHandler.sendMessage(message);
            }
        });

        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                fFmpegPlayer.setVolume(progress);
                tvCurrentVolume.setText("音量:" + progress + "%");
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        tvSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fFmpegPlayer.getDuration() > 0 && isSeekBar) {
                    currentPosition = fFmpegPlayer.getDuration() * progress / 100;
                }
                Log.e(TAG, "onProgressChanged: duration "+ fFmpegPlayer.getDuration());
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                isSeekBar=true;
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                isSeekBar=false;
                fFmpegPlayer.seek(currentPosition);

            }
        });

        playTimeHandler=new PlayTimeHandler(new WeakReference<>(this));
    }

    @OnClick({R.id.tv_play, R.id.tv_pause, R.id.tv_resume, R.id.tv_stop, R.id.btn_channel_left, R.id.btn_channel_right, R.id.btn_channel_center})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_play:
                String parentPath = Environment.getExternalStorageDirectory().getPath();
                /**
                 * 模拟器
                 */
                File file = new File(parentPath + "/鲨雕旭影视-被超Ａ鬼神小姐姐保护是什么体验(超清).mp4");
//                File file = new File(parentPath + "/xjj.mp4");
//                File file = new File(parentPath + "/video.mp4"); //播放有问题

                /**
                 * 测试手机
                 */
//                File file = new File(parentPath + "/ffmpeg/xjj.mp4");     //有问题
//                File file = new File(parentPath + "/ffmpeg/video.mp4");  // 有问题
//                File file = new File(parentPath + "/ffmpeg/鲨雕旭影视-被超Ａ鬼神小姐姐保护是什么体验(超清).mp4");
                if (!file.exists()) {
                    return;
                }
                Log.e("filepath ", file.getPath());
                fFmpegPlayer.setSource(file.getPath());
//                fFmpegPlayer.setSource("http://mpge.5nd.com/2015/2015-11-26/69708/1.mp3");
                fFmpegPlayer.parpared();
                break;
            case R.id.tv_pause:
                fFmpegPlayer.pause();
                break;
            case R.id.tv_resume:
                fFmpegPlayer.resume();
                break;
            case R.id.tv_stop:
                fFmpegPlayer.stop();
                break;
            case R.id.btn_channel_left:
                fFmpegPlayer.setMute(MuteEnum.MUTE_LEFT);
                break;
            case R.id.btn_channel_right:
                fFmpegPlayer.setMute(MuteEnum.MUTE_RIGHT);
                break;
            case R.id.btn_channel_center:
                fFmpegPlayer.setMute(MuteEnum.MUTE_CENTER);
                break;
        }
    }



    static class PlayTimeHandler extends Handler {
        private WeakReference<VideoPlayActivity> weakReference;

        public PlayTimeHandler(WeakReference<VideoPlayActivity> weakReference) {
            this.weakReference = weakReference;
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    VideoTimeInfo timeInfo = (VideoTimeInfo) msg.obj;
                    if (null != weakReference.get() && !weakReference.get().isSeekBar) {

                        if (null != weakReference.get().tvCurrentTime
                        ) {
                            weakReference.get().tvCurrentTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getCurrentTime()));
                        }
                        if (null != weakReference.get().tvCurrentTime) {
                            weakReference.get().tvTotalTime.setText(TimeUtil.secdsToDateFormat(timeInfo.getTotalTime()));
                        }
                        if (null != weakReference.get().tvSeekBar) {
                            weakReference.get().tvSeekBar.setProgress(
                                    timeInfo.getCurrentTime() * 100 / timeInfo.getTotalTime()

                            );
                        }
                    }
                    break;
            }

        }
    }
}
